package utils;

import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.filechooser.FileSystemView;

public class FileIconManager {

	private static final String FILE_ICONS_SUBFOLDER = "file" ;
	
	
	/**
	 * Get the file path corresponding to a file extension
	 * 
	 * @param extension
	 * @return
	 */
	private static String getFileIconPath (String extension) {
		return Configuration.getImageFolder() + File.separator + FILE_ICONS_SUBFOLDER + File.separator + extension + ".png" ;
	}
	
	/**
	 * Save the icon for the specified file extension
	 * 
	 * @param icon
	 * @param extension
	 */
	private static Icon saveFileIcon (Icon icon, String extension) {
        BufferedImage image = GraphicsEnvironment.getLocalGraphicsEnvironment()
        		.getDefaultScreenDevice().getDefaultConfiguration()
        		.createCompatibleImage(icon.getIconWidth(), icon.getIconHeight());
        Graphics2D g = image.createGraphics();
        icon.paintIcon(null, g, 0, 0);
        g.dispose();
		try {
			ImageIO.write(image, "png", new File(getFileIconPath(extension)));
		} 
		catch (IOException e) {
			e.printStackTrace();
		}
		return icon ;
	}
	
	/**
	 * Get the icon path corresponding to the specified file, create the icon if the icon does not exist.
	 * 
	 * @param file
	 * @return
	 * @throws IOException 
	 */
	public static String getFileIcon (String filename) throws IOException {
		String name = null ;
		if (filename.indexOf(".") != -1) {
			name = filename.substring(0, filename.lastIndexOf(".")) ;
		}
		else {
			name = filename ;
		}
		String extension = filename.substring(filename.lastIndexOf(".") + 1) ;
		File iconFile = new File(getFileIconPath(extension)) ;
		if (!iconFile.exists()) {
			iconFile.createNewFile() ;
			saveFileIcon (FileSystemView.getFileSystemView().getSystemIcon(File.createTempFile(name, "." + extension)), extension) ;
		}
		return getFileIconPath(extension) ;
	}
	
	public static void main (String[] args) throws IOException {
		System.out.println(getFileIcon("xxxxx.docx")) ;
	}
	
}
